package org.jeecg.modules.htxincailiao.industry.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTMember;
import org.jeecg.modules.htxincailiao.account.entity.HTMerchant;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.account.service.IHTMemberService;
import org.jeecg.modules.htxincailiao.account.service.IHTMerchantService;
import org.jeecg.modules.htxincailiao.industry.domain.dto.HTIndustryCheckDTO;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryMeeting;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryMeetingCheck;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryMeetingCheckService;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryMeetingService;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTOrderVO;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: ht_industry_meeting_check
 * @Author: jeecg-boot
 * @Date: 2021-12-21 17:55:12
 * @Version: V1.0
 */
@Api(tags = "ht_industry_meeting_check")
@RestController
@RequestMapping("/industry/hTIndustryMeetingCheck")
@Slf4j
public class HTIndustryMeetingCheckController extends JeecgController<HTIndustryMeetingCheck, IHTIndustryMeetingCheckService> {
    @Resource
    private IHTIndustryMeetingCheckService hTIndustryMeetingCheckService;

    @Resource
    private IHTIndustryMeetingService industryMeetingService;

    @Resource
    private IHTAccountService accountService;

    @Resource
    private IHTMemberService memberService;


    @Resource
    private IHTMerchantService merchantService;


    /**
     * 分页列表查询
     *
     * @param hTIndustryMeetingCheck
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-分页列表查询")
    @ApiOperation(value = "ht_industry_meeting_check-分页列表查询", notes = "ht_industry_meeting_check-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTIndustryMeetingCheck hTIndustryMeetingCheck,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTIndustryMeetingCheck> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustryMeetingCheck, req.getParameterMap());
        Page<HTIndustryMeetingCheck> page = new Page<HTIndustryMeetingCheck>(pageNo, pageSize);
        IPage<HTIndustryMeetingCheck> pageList = hTIndustryMeetingCheckService.page(page, queryWrapper);

        List<HTIndustryMeetingCheck> list = pageList.getRecords();
        for (HTIndustryMeetingCheck check : list) {
            HTMember user = memberService.getById(check.getUserId());
            if (oConvertUtils.isNotEmpty(user)) {
                check.setPhoneNumber(user.getPhoneNumber());
            } else {
                HTMerchant merchant = merchantService.getById(check.getUserId());
                if (oConvertUtils.isNotEmpty(merchant)) {
                    check.setPhoneNumber(merchant.getPhoneNumber());
                    check.setEnterpriseName(merchant.getEnterpriseName());
                }
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param dto
     * @param req
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-分页列表查询")
    @ApiOperation(value = "ht_industry_meeting_check-分页列表查询", notes = "ht_industry_meeting_check-分页列表查询")
    @PostMapping(value = "/orderedList")
    public Result<?> queryOrderedList(HttpServletRequest req, @RequestBody HTIndustryCheckDTO dto) {

        Result<List<HTIndustryMeetingCheck>> result = new Result<>();
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (oConvertUtils.isNotEmpty(user)) {
            List<HTIndustryMeetingCheck> list = hTIndustryMeetingCheckService.findAll(dto.getMeetingId(), user.getId());
            result.setResult(list);
        } else {
            result.error500("请选登录");
        }

        return result;
    }

    /**
     * 分页列表查询
     *
     * @param hTIndustryMeetingCheck
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-分页列表查询")
    @ApiOperation(value = "ht_industry_meeting_check-分页列表查询", notes = "ht_industry_meeting_check-分页列表查询")
    @RequestMapping(value = "/userAppliedList", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> queryPageUserAppliedList(HTIndustryMeetingCheck hTIndustryMeetingCheck,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                              HttpServletRequest req) {
        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                hTIndustryMeetingCheck = JSONObject.parseObject(line, HTIndustryMeetingCheck.class);
                pageNo = oConvertUtils.isNotEmpty(hTIndustryMeetingCheck.getPageNo()) ? hTIndustryMeetingCheck.getPageNo() : pageNo;
                pageSize = oConvertUtils.isNotEmpty(hTIndustryMeetingCheck.getPageSize()) ? hTIndustryMeetingCheck.getPageSize() : pageSize;
            }
        }

        Result<IPage<HTOrderVO>> result = new Result<>();
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (oConvertUtils.isNotEmpty(user)) {
            hTIndustryMeetingCheck.setUserId(user.getId());
        }

        QueryWrapper<HTIndustryMeetingCheck> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustryMeetingCheck, req.getParameterMap());
        Page<HTIndustryMeetingCheck> page = new Page<HTIndustryMeetingCheck>(pageNo, pageSize);
        IPage<HTIndustryMeetingCheck> pageList = hTIndustryMeetingCheckService.page(page, queryWrapper);

        return Result.OK(pageList);
    }


    /**
     * 编辑
     *
     * @param dto
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-编辑")
    @ApiOperation(value = "ht_industry_meeting_check-编辑", notes = "ht_industry_meeting_check-编辑")
    @PostMapping(value = "/getUserCheck")
    public Result<?> getUserCheck(HttpServletRequest req, @Valid @RequestBody HTIndustryCheckDTO dto) {
        Result<HTIndustryMeetingCheck> result = new Result<>();
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

        if (oConvertUtils.isNotEmpty(user)) {
            HTIndustryMeetingCheck check = hTIndustryMeetingCheckService.queryByUser(dto.getMeetingId(), user.getId());
            result.setResult(check);
        } else {
            result.error500("请先登录");
        }
        return result;
    }


    /**
     * 编辑
     *
     * @param dto
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-编辑")
    @ApiOperation(value = "ht_industry_meeting_check-编辑", notes = "ht_industry_meeting_check-编辑")
    @PostMapping(value = "/userCheckIn")
    public Result<?> userCheckIn(HttpServletRequest req, @Valid @RequestBody HTIndustryCheckDTO dto) {
        Result<HTIndustryMeetingCheck> result = new Result<>();
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

        if (oConvertUtils.isNotEmpty(user)) {
            HTIndustryMeeting meeting = industryMeetingService.getById(dto.getMeetingId());
            HTIndustryMeetingCheck check = hTIndustryMeetingCheckService.queryByUser(dto.getMeetingId(), user.getId());
            if (isPaymentMeeting(meeting)) {
                check = handlePaymentMeetingCheck(dto, user, check);
                result.setResult(check);
            } else {

                HTIndustryMeetingCheck checkedInCheck = handleFreeMeetingCheck(dto, user, check);
                if (oConvertUtils.isNotEmpty(checkedInCheck)) {
                    result.setResult(checkedInCheck);
                }
            }
        } else {
            result.error500("请先登录");
        }
        return result;
    }

    private HTIndustryMeetingCheck handleFreeMeetingCheck(HTIndustryCheckDTO dto,
                                                          HTPlatformUser user,
                                                          HTIndustryMeetingCheck check) {
        if (oConvertUtils.isEmpty(check)) {
            check = hTIndustryMeetingCheckService.queryByBuyerId(dto.getMeetingId(), user.getId());
            //免费会议 check为空时自动创建check 自动签到
            if (oConvertUtils.isEmpty(check)) {
                check = new HTIndustryMeetingCheck();
                check.setBuyerId(user.getId());
                check.setMeetingId(dto.getMeetingId());

                try {
                    hTIndustryMeetingCheckService.save(check);
                } catch (Exception e) {
                    throw new JeecgBootException("签到失败请稍后尝试");
                }
            }
        }
        updateCheck(dto, user, check);
        return check;
    }

    private HTIndustryMeetingCheck handlePaymentMeetingCheck(HTIndustryCheckDTO dto,
                                                             HTPlatformUser user,
                                                             HTIndustryMeetingCheck check) {
//        System.out.printf("\n\n\n handlePaymentMeetingCheck %s \n\n\n", JSONObject.toJSONString(check));
        boolean success = false;
//        验证码未签到
        if (oConvertUtils.isEmpty(check)) {
            if (oConvertUtils.isNotEmpty(dto.getCode())) {
                check = hTIndustryMeetingCheckService.queryByCode(dto.getMeetingId(), dto.getCode());
            } else {
                throw new JeecgBootException("入场码不能为空");
            }
        }

        if (oConvertUtils.isNotEmpty(check)) {
            success = updateCheck(dto, user, check);
        } else {
            throw new JeecgBootException("未报名或入场码有误");
        }

        return check;
    }

    private boolean updateCheck(HTIndustryCheckDTO dto,
                                HTPlatformUser user,
                                HTIndustryMeetingCheck check) {
        boolean success = false;
        Integer checkSerialNumber = hTIndustryMeetingCheckService.getCheckSerialNumber(dto.getMeetingId());

        check.setMeetingId(dto.getMeetingId());
        check.setUserId(user.getId());
        check.setCode(check.getCode());
        check.setIsCheckedIn(1);

        if (check.getCheckSerialNumber() == 0) {
            check.setCheckSerialNumber(checkSerialNumber);
        }

        if (oConvertUtils.isNotEmpty(dto.getEnterpriseName())) {
            check.setEnterpriseName(dto.getEnterpriseName());
        }

        if (oConvertUtils.isNotEmpty(dto.getParticipant())) {
            check.setParticipant(dto.getParticipant());
        } else {
            String participant = user.getRealName();
            if (oConvertUtils.isEmpty(participant)) participant = user.getPhoneNumber();
            if (oConvertUtils.isEmpty(participant)) participant = user.getUsername();
            check.setParticipant(participant);
        }
        try {
            success = hTIndustryMeetingCheckService.updateById(check);
        } catch (Exception e) {
            throw new JeecgBootException("签到失败请稍后尝试");
        }

        return success;
    }

    private boolean isPaymentMeeting(HTIndustryMeeting meeting) {
        return oConvertUtils.isNotEmpty(meeting) &&
                oConvertUtils.isNotEmpty(meeting.getAudienceCost()) &&
                meeting.getAudienceCost().floatValue() > 0;
    }

    /**
     * 添加
     *
     * @param hTIndustryMeetingCheck
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-添加")
    @ApiOperation(value = "ht_industry_meeting_check-添加", notes = "ht_industry_meeting_check-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HTIndustryMeetingCheck hTIndustryMeetingCheck) {
        hTIndustryMeetingCheckService.save(hTIndustryMeetingCheck);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hTIndustryMeetingCheck
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-编辑")
    @ApiOperation(value = "ht_industry_meeting_check-编辑", notes = "ht_industry_meeting_check-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTIndustryMeetingCheck hTIndustryMeetingCheck) {
        hTIndustryMeetingCheckService.updateById(hTIndustryMeetingCheck);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-通过id删除")
    @ApiOperation(value = "ht_industry_meeting_check-通过id删除", notes = "ht_industry_meeting_check-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hTIndustryMeetingCheckService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-批量删除")
    @ApiOperation(value = "ht_industry_meeting_check-批量删除", notes = "ht_industry_meeting_check-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hTIndustryMeetingCheckService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_industry_meeting_check-通过id查询")
    @ApiOperation(value = "ht_industry_meeting_check-通过id查询", notes = "ht_industry_meeting_check-通过id查询")
    @RequestMapping(value = "/queryById", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> queryById(HttpServletRequest req, @RequestParam(name = "id", required = false) String id) {
        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                HTIndustryMeetingCheck hTIndustryMeetingCheck = JSONObject.parseObject(line, HTIndustryMeetingCheck.class);
                id = hTIndustryMeetingCheck.getId();
            }
        }

        HTIndustryMeetingCheck hTIndustryMeetingCheck = hTIndustryMeetingCheckService.getById(id);
        if (hTIndustryMeetingCheck == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTIndustryMeetingCheck);
    }

    /**
     * 导出excel
     *
     * @param req
     * @param hTIndustryMeetingCheck
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest req, HTIndustryMeetingCheck hTIndustryMeetingCheck) {
        QueryWrapper<HTIndustryMeetingCheck> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustryMeetingCheck, req.getParameterMap());
        Page<HTIndustryMeetingCheck> page = new Page<HTIndustryMeetingCheck>(1, 99999999);
        IPage<HTIndustryMeetingCheck> pageList = hTIndustryMeetingCheckService.page(page, queryWrapper);

        List<HTIndustryMeetingCheck> list = pageList.getRecords();
        for (HTIndustryMeetingCheck check : list) {
            HTPlatformUser user = accountService.queryUserById(check.getUserId());
            if (oConvertUtils.isNotEmpty(user)) {
                check.setPhoneNumber(user.getPhoneNumber());
            }

        }

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "ht_industry_meeting_check");
        mv.addObject(NormalExcelConstants.CLASS, HTIndustryMeetingCheck.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ht_industry_meeting_check", "导出人：admin", "ht_industry_meeting_check"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);

        return mv;


//        return super.exportXls(req, hTIndustryMeetingCheck, HTIndustryMeetingCheck.class, "ht_industry_meeting_check");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTIndustryMeetingCheck.class);
    }

}
